// pages/scratchInsurance/scratchInsurance.js
var Auth = require('../../utils/auth.js');
Page({

    /**
     * 页面的初始数据
     */
    data: {
        TabList:['保险证书', '常见问题','申请列表'],
        windowWidth: 100,
        windowHeight: 100,
        detail: {},
        tab_index_0: true,
        tab_index_1: false,
        tab_index_2: false,
        tab_index_3: false,
        common_problem: [{
            id: "1",
            ask: '理赔政策是什么？',
            answer: "1、1年保障有效期内，累计补膜米数不超过15米，不限次数。\n "+
                    "2、当发生单方或者多方事故时，车辆因意外碰撞、剐蹭导致的车衣受损。\n"+
                    "3、理赔金额为当次需补膜的材料费用，客户仅需支付局部施工费用。",
            isExpanded: false
        }, {
            id: "2",
            ask: '理赔流程是什么？',
            answer: '1、膜破损后，消费者到凌膜授权门店说明情况。\n 2、门店查勘定损，属实则进行补膜，在小程序发起补膜申请并上传照片。\n 3、审批情况是否属实，如鉴定真实则审批通过，补膜米数生效，本次补膜流程结束。',
            isExpanded: false
        }, {
            id: "3",
            ask: '剐蹭险和质保有什么区别？',
            answer: '凌膜车衣剐蹭险是凌膜厂家专门针对旗下隐形车衣推出的补膜保险，针对用户在碰撞中剐蹭而需要局部更换膜时，提供免费补膜服务，和质保不同，主要体现在：\n 1、承诺不同：前者是针对车衣膜破损的保障；后者是对车衣大范围翘边、脱胶、开裂、起泡、分层、严重黄变的承诺。\n 2、产品不同：前者只针对车衣，后者是车衣、改色和太阳膜必备的保',
            isExpanded: false
        }, {
            id: "4",
            ask: '异地怎么理赔？',
            answer: '在全国范围内，只要是我们的凌膜授权门店，都是可以为您提供补膜服务的门店。您可以到店正常享受补膜服务。',
            isExpanded: false
        }, {
            id: "5",
            ask: '补膜门店有哪些？',
            answer: '只要是我们的凌膜授权门店，都是可以为您提供补膜服务的门店。您可以通过致电或者联系官方客户获取最新门店明细。',
            isExpanded: false
        }
        // , {
        //     id: "6",
        //     ask: '怎么续保？',
        //     answer: 'JK35',
        //     isExpanded: false
        // },
        ],
        name:'',
        length:0,
        position:'',
        apply_date: '请选择申请时间',
        files: [],
        repair_files: [],
        array2: ["-请选择车辆品牌-", "奥迪", "宝马", "奔驰", "丰田"],
        filterList: [],
        filterEmpty: false,
        cheliangpinpai: -1,
        repair_list:[]
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad(options) {
        var self = this;
        wx.getSystemInfo({
            success: (result) => {
                self.setData({
                    windowHeight: result.windowHeight,
                    windowWidth: result.windowWidth
                })
                if (result.inFinChat) {
                    self.setData({
                        inFinChat: result.inFinChat
                    })
                } else {
                    Auth.setUserInfoData(self);
                    Auth.checkLogin(self);
                    Auth.checkSession(self, 'isLoginNow');
                }
            },
        })
        //根据用户来判断是否有申请补膜tab
        if(self.data.userInfo.user_type == 1){
            let newTabList = self.data.TabList.concat('申请补膜');
            wx.request({
                url: "https://a.ygtape.com.cn/index.php/qualityassurance/index/get_assurance_info",
                method: "POST",
                header: {
                    "content-type": "application/x-www-form-urlencoded",
                }, 
                success: function (res) {
      18
                    self.setData({
                        array2: res.data.data,
                        cheliangpinpaiToSearchTip: `当前共有 ${res.data.data.length} 条车辆品牌信息`
                    });
                },
            });

            wx.request({
                url: "https://a.ygtape.com.cn/index.php/qualityassurance/index/get_scratch_repair_list",
                method: "POST", 
                data:{mobile:self.data.userInfo.user_mobile},
                header: {
                    "content-type": "application/x-www-form-urlencoded",
                }, 
                success: function (res) { 
                    let rows = res.data.data.rows;
           
                    self.setData({ 
                        repair_list:rows
                    }); 
                },  
            });

            self.setData({ 
                name:self.data.userLevel.levelName,
                TabList: newTabList
            })
        }
        wx.request({
            url: 'https://a.ygtape.com.cn/index.php/qualityassurance/index/get_scratch',
            method: 'POST',
            data: {
                mobile: self.data.userInfo.user_mobile
            },
            header: {
                'content-type': 'application/x-www-form-urlencoded'
            },
            success: function (res) {
                let res_data = res.data;
                if (res_data.code == 0) {

                    self.setData({
                        detail: res_data.data
                    })
                } else {
                    self.$showDialog({
                        title: '提示',
                        content: res_data.message,
                        success: res => {

                            if (res.confirm) {
                                this.$success({
                                    title: '点击了确定'
                                })
                            } else {
                                wx.showToast({
                                    title: '点击了取消',
                                    icon: 'none'
                                })
                            }
                        }
                    })
                }


            }
        })

    },
    tabNavChange: function (options) {
        let that = this;
        // return false;
        //切换菜单
        let selectd_index = options.detail.index;
        switch (selectd_index) {
            case 0:
                that.setData({
                    tab_index_0: true,
                    tab_index_1: false,
                    tab_index_2: false,
                    tab_index_3: false,
                });
                break;
            case 1:
                that.setData({
                    tab_index_0: false,
                    tab_index_1: true,
                    tab_index_2: false,
                    tab_index_3: false,
                });
                break;
            case 2:
                that.setData({
                    tab_index_0: false,
                    tab_index_1: false,
                    tab_index_2: true,
                    tab_index_3: false,
                });
                break;
            case 3:
                that.setData({
                    tab_index_0: false,
                    tab_index_1: false,
                    tab_index_2: false,
                    tab_index_3: true,
                });
                break;
        }
    },
    togglePanel: function (e) {
        var that = this;

        var _id = e.currentTarget.dataset.id;

        var common_problem = that.data.common_problem;
        for (let i = 0; common_problem.length > i; i++) {
            if (common_problem[i].id == _id) {
                that.setData({
                    ['common_problem[' + i + '].isExpanded']: !common_problem[i].isExpanded,
                })
            }
        }


    },
    bindDateChange: function (e) {

        this.setData({
            apply_date: e.detail.value
        })
    },

    handleChooseImage: function (e) {
        var name  =  e.currentTarget.dataset.name;
        var that = this;
        // 选择图片
        wx.chooseMedia({
            count: 4,
            mediaType: ['image'],
            sourceType: ['album', 'camera'],
            camera: 'back',
            // sizeType:['compressed'],  // 选择压缩图
            success(res) {
                res.tempFiles.forEach((element) => {
                    wx.uploadFile({
                        url: 'https://a.ygtape.com.cn/index.php/qualityassurance/index/upload', //仅为示例，非真实的接口地址
                        filePath: element.tempFilePath,
                        name: 'file',
                        formData: {
                            'mobile': that.data.userInfo.user_mobile,
                            'token': that.data.userInfo.token,
                        },
                        success: function (res) {
                            res.data = JSON.parse(res.data);
                            if (res.data.status == 200) {
                                that.setData({
                                    [name]: [...that.data[name], res.data.url]
                                })
                            } else {
                                wx.showToast({
                                    title: '上传失败',
                                    icon: 'error',
                                    duration: 1000
                                });
                            }
                        }
                    })
                })      
                
            }
        })
    },
    // 删除图片
    handleDeleteImage: function (e) {
      
    
        const { index } = e.currentTarget.dataset
        let files = [...this.data.files]
        console.log(files);
        files.splice(index, 1)
        this.setData({
            files
        })
    },
    handleDeleteImageRepair: function (e) {
      
        const { index } = e.currentTarget.dataset
        let repair_files = [...this.data.repair_files]
    
        repair_files.splice(index, 1)
        this.setData({
            repair_files
        })
    },
    getinputVlue: function (e) {
        var self = this;
        var name = e.currentTarget.dataset.name;
        self.setData({
            [name]: e.detail.value,
        });
    },

     // 滚动视图点击事件
     scroolViewClick(event) {
        let { index, name } = event.currentTarget.dataset;
        this.setData({ cheliangpinpai: index, cheliangpinpaiName: name });
    },

    // 获取输入框输入字符
    getInputVal(event) {
        let inputVal = event.detail.value, len, cheliangpinpaiToSearch = inputVal.toUpperCase(),
            cheliangpinpaiToSearchTip, filterListTemp = [], { array2 } = this.data;
        len = cheliangpinpaiToSearch.length;

        if (len == 0) {
            cheliangpinpaiToSearchTip = `当前共有 ${array2.length} 条车辆品牌信息`;
        }

        for (let i = 0; i < array2.length; i++) {
            if (array2[i].indexOf(cheliangpinpaiToSearch) != -1)
                filterListTemp.push(array2[i]);
        }

        if (filterListTemp.length == 0) {
            cheliangpinpaiToSearchTip = "输入的关键字还没有相关的车辆品牌！";
        } else if (filterListTemp.length != 0 && inputVal != "") {
            cheliangpinpaiToSearchTip = `当前过滤到 ${filterListTemp.length} 条车辆品牌信息`;
        }
        this.setData({
            cheliangpinpaiToSearch,
            cheliangpinpaiToSearchTip,
            filterList: filterListTemp,
        });
    },

    // 选定车辆品牌确定按钮
    cheliangpinpaiToSure(res) {
        const { detail } = res, { filterList, array2, cheliangpinpaiName } = this.data;
        if (detail.cancel) {
            this.setData({
                cheliangpinpai: "-1",
                cheliangpinpaiToSearch: '',
                filterList: [],
                cheliangpinpaiToSearchTip :`当前共有 ${array2.length} 条车辆品牌信息`
            })
        };
        if (detail.confirm) {
            this.setData({
                cheliangpinpai: array2.indexOf(cheliangpinpaiName),
                cheliangpinpaiToSearch: '',
                filterList: [],
                
            });
        }
    },
    // 激活车辆品牌模态窗口
    cheliangpinpaiChange() {
        this.setData({ modalType: "cheliangpinpai" });
    },
    tips_msg(msg, time = 1000, icon = 'none') {
        wx.showToast({
            icon: icon,
            title: msg,
            duration: time
        });
    },
    handleClickSubmit:function(e){
        //现在开始开发
        var that = this;
        var current_data = that.data;
        
        var ins_data = {};
        if(current_data.cheliangpinpai == -1){
            that.tips_msg('请选择补膜人员');
            return
        }
        ins_data.repair_people = current_data.array2[current_data.cheliangpinpai];
        
        ins_data.app_mobile = current_data.userInfo.user_mobile;

        ins_data.name = current_data.name;


        ins_data.apply_date = current_data.apply_date;
        if (!current_data.length) {
            that.tips_msg('补膜米数必填');
            return
        }
        if (Number.isNaN(Number(current_data.length))) {
            that.tips_msg('补膜米数类型必须为数字');
            return
        }
        ins_data.length = current_data.length;
        if (!current_data.position) {
            that.tips_msg('部位为必填');
            return
        }
        ins_data.position = current_data.position;
        ins_data.files = current_data.files;
        if(current_data.files.length == 0){
            this.tips_msg('汽车破损部位照片必须上传一张');
             return
        }
        //当前门店账号也要存一份

        
        ins_data.repair_files = current_data.repair_files;
        if(current_data.repair_files.length < 2){
            this.tips_msg('车票照片+车架照片必须上传');
             return
        }

 
        wx.request({
            url: "https://a.ygtape.com.cn/index.php/qualityassurance/index/add_scratch",
            method: "POST",
            data: ins_data,
            header: {
                "content-type": "application/x-www-form-urlencoded",
            },
            success: function (res) {
                console.log(res.data);
                if (res.data.status == 200) {
                    wx.showToast({
                        title: "新增成功",
                        duration: 2000,
                    });
                } else {
                    wx.showToast({
                        title: res.data.message,
                        duration: 2000,
                        icon:"none"
                    });
                }
            },
        });

       
    },
    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady() {  

    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow() {

    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide() {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload() {

    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh() {

    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom() {

    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage() {

    }
})